function findBraceEndIndex(s, begin) {
    var left = []
    var right = []
    for (var i = 0; i < s.length; i++) {
        if (s[i] === '[') left.push(i);
        if (s[i] === ']') right.push(i);
    }
    return right.reverse()[left.indexOf(begin)]
}

function interpreter(code, tape) {
    var p = 0;
    var mem = tape.split('');
    var loops = []
    for (var i = 0; i < code.length; i++) {
        var cmd = code[i];
        switch (cmd) {
            case '>':p++;break;
            case '<':p--;break;
            case '*':mem[p] ^= 1;break;
            case '[':
                if (mem[p] != '0') loops.push(i);else i = findBraceEndIndex(code, i);
                break;
            case ']':
                i = loops[loops.length - 1]
                break;
        }

        if (p >= mem.length || p < 0) return mem.join('')
    }
    return mem.join('')
}
